﻿using System;

namespace dPet.Domain.Models
{
	using Hangerd;
	using Hangerd.Entity;
	using Hangerd.Utility;

	public class Staff : EntityBase
	{
		#region Public Properties

		/// <summary>
		/// 所属医院ID
		/// </summary>
		public string HospitalId { get; private set; }

		/// <summary>
		/// 登录邮箱
		/// </summary>
		[RecordModify]
		public string LoginName { get; private set; }

		/// <summary>
		/// 登录密码（加密后）
		/// </summary>
		public string EncryptedPassword { get; private set; }

		/// <summary>
		/// 用于密码加密Salt
		/// </summary>
		public string Salt { get; private set; }

		/// <summary>
		/// 角色
		/// </summary>
		public virtual StaffRole StaffRole { get; set; }

		/// <summary>
		/// 姓名
		/// </summary>
		[RecordModify]
		public string Name { get; set; }

		/// <summary>
		/// 联系方式
		/// </summary>
		[RecordModify]
		public string Contact { get; set; }

		#endregion

		#region Constructors

		private Staff() { }

		public Staff(Hospital hospital, string loginName, string unencryptedPassword, StaffRole staffRole)
		{
			if (!ValidationHelper.IsEmailAddress(loginName))
			{
				throw new HangerdException("登录名须为邮箱地址");
			}

			this.HospitalId = hospital.Id;
			this.LoginName = loginName;
			this.EncryptedPassword = this.GetEncryptedPassword(unencryptedPassword);
			this.StaffRole = staffRole;
		}

		#endregion

		#region Public Methods

		public bool ValidatePassword(string unencryptedPassword)
		{
			var encryptedPassword = this.GetEncryptedPassword(unencryptedPassword);

			return encryptedPassword.Equals(this.EncryptedPassword);
		}

		public void ChangePassword(string unencryptedPassword)
		{
			this.EncryptedPassword = this.GetEncryptedPassword(unencryptedPassword);
		}

		#endregion

		#region Private Methods

		private string GetEncryptedPassword(string unencryptedPassword)
		{
			if (string.IsNullOrWhiteSpace(unencryptedPassword))
			{
				throw new HangerdException("密码不可为空");
			}

			if (string.IsNullOrWhiteSpace(this.Salt))
			{
				this.Salt = this.GenerateSalt();
			}

			return CryptoHelper.GetMd5(string.Concat(unencryptedPassword, this.Salt));
		}

		private string GenerateSalt()
		{
			return Guid.NewGuid().ToString("N").Substring(0, 10);
		}

		#endregion
	}
}
